//
//  YPContentItemView.m
//  ChengHuiTong
//
//  Created by CHT-Technology on 2017/2/21.
//  Copyright © 2017年 张文权. All rights reserved.
//

#import "YPContentItemView.h"
#import "CALayer+Anim.h"

@interface YPContentItemView (){
    
    
}

@property (nonatomic,strong)UITableView *hkTableView;
@property (nonatomic,strong)UIControl *hkControl;
@property (nonatomic,weak)NSArray *hkDataArray;

@end

@implementation YPContentItemView

- (instancetype)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    if (self) {
        
        [self setUp];
    }
    
    return self;
}
- (instancetype)init{
    
    self = [super init];
    if (self) {
        
        [self setUp];
    }
    
    return self;
}
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    
    self = [super initWithCoder:aDecoder];
    if (self) {
        
        [self setUp];
    }
    return self;
}
- (instancetype)initWithFrame:(CGRect)frame style:(UITableViewStyle)style{
    
    self = [super initWithFrame:frame style:style];
    if(self){
        
        [self setUp];
    }
    return self;
}

#pragma mark -- privateMethod
- (void)setUp{
    
    self.separatorStyle = 0;
    self.delegate = self;
    self.dataSource = self;
    self.tableFooterView = [UIView new];
    
    WeakSelf
    [self addGifHeaderWithRefreshingBlock:^{
        weakSelf.configModel.page = 1;
        [weakSelf setUpData];
    }];
    
    self.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.configModel.page ++;
        [weakSelf setUpData];
    }];
    
    self.footer.hidden = YES;
    
}

- (void)setUpData{
    NSLog(@"%@,%ld",self.configModel.title,(long)self.configModel.page);
    
    [YPHttpRequestMethod sendAsyRequestURL:[self getUrlString] withData:@{@"token":TOKEN,@"page":@(self.configModel.page)} withCompletionBlock:^(NSDictionary *responseDictionary) {
        
        [self.header endRefreshing];
        [self.footer endRefreshing];
        if ([responseDictionary[@"status"] integerValue] == 0) {
            
            [self configModelsWithDataArray:responseDictionary[@"list"]];
            
        }
        [self reloadData];
        
    } withFailedBlock:^(NSError *error) {
        
        [self.header endRefreshing];
        [self.footer endRefreshing];
        [self reloadData];
        
    }withIndicator:NO  atView:self];
}

- (NSString *)getUrlString{
    
    NSString *urlString;
    if ([self.configModel.title isEqualToString:@"可转让"]) {
        urlString = CMD_ZQKZR;
    }else if ([self.configModel.title isEqualToString:@"转让中"]){
        urlString = CMD_ZQZRZ;
    }else if ([self.configModel.title isEqualToString:@"已转让"]){
        urlString = CMD_ZQYZR;
    }else if ([self.configModel.title isEqualToString:@"已认购"]){
        urlString = CMD_ZQYRG;
    }
    return urlString;
}

- (NSString *)getModelClassString{
    
    NSString *modelClassString;
    if ([self.configModel.title isEqualToString:@"可转让"]) {
        modelClassString = @"YPZQRecordModel";
    }else if ([self.configModel.title isEqualToString:@"转让中"]){
        modelClassString = @"YPZQZRZModel";
    }else if ([self.configModel.title isEqualToString:@"已转让"]){
        modelClassString = @"YPZQYZRModel";
    }else if ([self.configModel.title isEqualToString:@"已认购"]){
        modelClassString = @"YPZQYRGModel";
    }
    return modelClassString;
}

- (void)configModelsWithDataArray:(NSArray *)dataArray{
    
    if (self.configModel.page == 1) {
        [self.configModel.dataArray removeAllObjects];
    }
    
    for (NSDictionary *dic in dataArray) {
        
        [self.configModel.dataArray addObject:[[NSClassFromString([self getModelClassString]) alloc]initWithDic:dic]];
    }
    
    if ([dataArray count] < 5) {
        [self.footer noticeNoMoreData];
    }
    
    self.footer.hidden = self.configModel.noData = self.configModel.dataArray.count==0?YES:NO;
    if (self.footer.hidden) {
        self.tableFooterView = [SelectView footViewWithheight:self.height];
    }else{
        self.tableFooterView = [UIView new];
    }
}

- (UIControl *)hkControl{
    
    if (!_hkControl) {
        _hkControl = [[UIControl alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _hkControl.backgroundColor = [UIColor colorWithWhite:0. alpha:0.5];
        [_hkControl addTarget:self action:@selector(removeHkTableView) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _hkControl;
}

- (UITableView *)hkTableView{
    
    if (!_hkTableView) {
        _hkTableView = [[UITableView alloc]initWithFrame:CGRectMake(leftMargin, (SCREEN_HEIGHT - autoScaleH(250))/2.f, SCREEN_WIDTH - leftMargin*2, autoScaleH(250)) style:UITableViewStylePlain];
        _hkTableView.delegate = self;
        _hkTableView.dataSource = self;
//        _hkTableView.tableFooterView = [UIView new];
        _hkTableView.bounces = NO;
        _hkTableView.allowsSelection = NO;
        _hkTableView.separatorInset = UIEdgeInsetsZero;
        _hkTableView.separatorColor = colorWithRGB(220, 220, 220);
    }
    
    return _hkTableView;
}

- (void)removeHkTableView{
    
    [_hkTableView removeFromSuperview];
    _hkTableView = nil;
    [_hkControl removeFromSuperview];
}

#pragma mark --UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (tableView == _hkTableView) {
        return _hkDataArray.count;
    }
    return self.configModel.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == _hkTableView) {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hkCell"];
        if (!cell) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"hkCell"];
            UILabel *timeLabel = [UILabel creatWithFrame:CGRectMake(0, 0, _hkTableView.width/5.f*1.5, 30)
                                                    font:[UIFont systemFontOfSize:12]
                                                    text:@""
                                               textColor:[UIColor darkGrayColor]
                                           textAlignment:1];
            timeLabel.tag = 1000;
            [cell.contentView addSubview:timeLabel];
            
            UILabel *moneyLabel = [UILabel creatWithFrame:CGRectMake(timeLabel.right, 0, timeLabel.width, 30)
                                                    font:[UIFont systemFontOfSize:12]
                                                    text:@""
                                               textColor:[UIColor darkGrayColor]
                                           textAlignment:1];
            moneyLabel.tag = 1001;
            [cell.contentView addSubview:moneyLabel];
            
            UILabel *qsLabel = [UILabel creatWithFrame:CGRectMake(moneyLabel.right, 0, _hkTableView.width/5.f, 30)
                                                    font:[UIFont systemFontOfSize:12]
                                                    text:@""
                                               textColor:[UIColor darkGrayColor]
                                           textAlignment:1];
            qsLabel.tag = 1002;
            [cell.contentView addSubview:qsLabel];
            
            UILabel *statusLabel = [UILabel creatWithFrame:CGRectMake(qsLabel.right, 0, qsLabel.width, 30)
                                                    font:[UIFont systemFontOfSize:12]
                                                    text:@""
                                               textColor:[UIColor darkGrayColor]
                                           textAlignment:1];
            statusLabel.tag = 1003;
            [cell.contentView addSubview:statusLabel];
            
        }
        
        UILabel *timeLabel = [cell.contentView viewWithTag:1000];
        UILabel *moneyLabel = [cell.contentView viewWithTag:1001];
        UILabel *qsLabel = [cell.contentView viewWithTag:1002];
        UILabel *statusLabel = [cell.contentView viewWithTag:1003];
        
        NSDictionary *dataDic = _hkDataArray[indexPath.row];
        timeLabel.text = dataDic[@"repay_date"];
        moneyLabel.text = dataDic[@"repay_account"];
        qsLabel.text = [NSString stringWithFormat:@"%@/%@",dataDic[@"periods"],dataDic[@"total_periods"]];
        statusLabel.text = [dataDic[@"status"] integerValue] == 0?@"还款中":@"已还款";
        statusLabel.textColor = [dataDic[@"status"] integerValue] == 0?kColor_redNumberColor:[UIColor darkGrayColor];
        
        return cell;
        
    }else{
        
        //根据数据模型来确定不同的重用符即可
        YPZQRecodeCell*cell = [tableView dequeueReusableCellWithIdentifier:self.configModel.title];
        if (!cell) {
            cell = [[YPZQRecodeCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:self.configModel.title];
            WeakSelf
            cell.applyBlock = ^(YPZQRecordModel *model){
                if (weakSelf.applyBlock) {
                    weakSelf.applyBlock(model);
                }
            };
            cell.hkDetailBlock = ^(NSArray *hkArray){
                
                weakSelf.hkDataArray = hkArray;
                [APPDelegate.window addSubview:weakSelf.hkControl];
                [APPDelegate.window addSubview:weakSelf.hkTableView];
                
                [weakSelf.hkTableView.layer scale];

            };
        }
        
        SEL sel = NSSelectorFromString([NSString stringWithFormat:@"set%@:",[self getModelClassString]]);
        if ([cell respondsToSelector:sel]) {
            id obj = self.configModel.dataArray[indexPath.row];
            if(obj)[cell performSelector:sel withObject:obj];
        }
        
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(tableView == _hkTableView) return 30;
    if ([self.configModel.title isEqualToString:@"可转让"]) {
        return 190;
    }else if ([self.configModel.title isEqualToString:@"转让中"] || [self.configModel.title isEqualToString:@"已转让"]) {
        return 140;
    }else{
        return 160;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    if (tableView == _hkTableView) {
        
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _hkTableView.width, 70)];
        view.backgroundColor = [UIColor whiteColor];
        [view addLine];
        UILabel *titleLabel = [UILabel creatWithFrame:CGRectMake(0, 0, _hkTableView.width, 40)
                                                 font:[UIFont systemFontOfSize:15]
                                                 text:@"还款明细"
                                            textColor:kColor_greyAshTitleColor
                                        textAlignment:1];
        [titleLabel addLine];
        [view addSubview:titleLabel];
        
        UIButton *closeBtn = [UIButton creatWithFrame:CGRectMake(titleLabel.width - 50, 0, 50, titleLabel.height)
                                                image:[UIImage imageNamed:@"close"]
                                               action:@selector(removeHkTableView)
                                               target:self];
        [view addSubview:closeBtn];
        
        NSArray *array = @[@"回款日期",@"回款金额(元)",@"期数",@"状态"];

        __block UILabel *tempLabel;
        [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            UILabel *label = [UILabel creatWithFrame:CGRectMake(tempLabel.right, titleLabel.bottom, idx > 1?_hkTableView.width/5.f:_hkTableView.width/5.f*1.5, 30)
                                                     font:[UIFont systemFontOfSize:14]
                                                     text:array[idx]
                                                textColor:kColor_greyAshTitleColor
                                            textAlignment:NSTextAlignmentCenter];
            tempLabel = label;
            [view addSubview:label];
        }];
        
        return view;
    }else if([self.configModel.title isEqualToString:@"可转让"]){
        
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, tableView.width, 45)];
        view.backgroundColor = UIColorFromRGB(0xf5f5f5);
        
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(leftMargin, 5, view.width - leftMargin*2, view.height)];
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = kColor_redNumberColor;
        label.text = @"债权人所持有的单笔债权必须一次性转让，即每笔债权只能一对一转让";
        label.numberOfLines = 0;
        [view addSubview:label];
        return view;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if(tableView == _hkTableView)
        return 70.f;
    else if ([self.configModel.title isEqualToString:@"可转让"])
        return 45;
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return 0.1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.tableViewDidSelectBlock) {
        self.tableViewDidSelectBlock();
    }

}



@end
